const Router = require('koa-router');

const r1 = new Router();

r1.get('', async (ctx) => {      // 请求根的时候，渲染list
    let page = 1;
    let page_size = 8;

    // LIMIT 0, 8  是分页的语句，这是一页8条
    let questions = await ctx.db.execute(`
        SELECT Q.ID, Q.title, ANSWER.content AS best_answer_content, AUTHOR.name, AUTHOR.headline, AUTHOR.img_url FROM

        question_table AS Q

        LEFT JOIN answer_table AS ANSWER ON Q.best_answer_ID = ANSWER.ID

        LEFT JOIN author_table AS AUTHOR ON ANSWER.author_ID = AUTHOR.ID

        LIMIT ${(page - 1) * page_size}, ${page_size}
    `);

    await ctx.render('list', {
        questions
    });
})

r1.get('detail/:id', async (ctx) => {
    let {id} = ctx.params;

    let question = await ctx.db.execute(`SELECT * FROM question_table WHERE ID=${id}`);

    let answers = await ctx.db.execute(`
        SELECT * FROM
        answer_table AS ANSWER
        LEFT JOIN author_table AS AUTHOR ON ANSWER.ID = AUTHOR.ID
        WHERE question_ID=${id}
    `);

    answers = answers.filter((answer) => {
        if (answer.ID == question[0].best_answer_ID) {
            question[0].best_answer = answer;
            return false;
        } else {
            return true;
        }
    });

    let topics = await ctx.db.execute(`
        SELECT * FROM topic_table WHERE ID IN (${question[0].topics})
    `);

    question = question[0];
    console.log(question);
        // console.log(answers);
        // console.log(topics);
    await ctx.render('item', {
        question,
        answers,
        topics
    })
})

module.exports = r1.routes();
